-- Lua Battle System - AI基类

local Logger = require("utils.logger")
local BattleConfig = require("config.battle_config")

local AI = {
    -- AI基本属性
    id = "",
    name = "",
    description = "",
    
    -- AI难度和性格
    difficulty = "normal", -- easy, normal, hard, expert
    personality = "aggressive", -- aggressive, defensive, balanced, tricky
    
    -- AI决策参数
    decision_time_limit = BattleConfig.ai.decision_time_limit,
    
    -- AI状态
    is_active = true,
    
    -- AI记忆
    memory = {
        previous_decisions = {},
        target_history = {},
        skill_usage_history = {}
    }
}

-- AI构造函数
function AI:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    o:init()
    return o
end

-- 初始化AI
function AI:init()
    self.is_active = true
    self.memory = {
        previous_decisions = {},
        target_history = {},
        skill_usage_history = {}
    }
    Logger.debug("AI初始化完成: " .. self.name)
end

-- 做出决策
function AI:make_decision(character, battle_state)
    if not self.is_active then
        Logger.warn("AI未激活，无法做出决策")
        return nil
    end
    
    Logger.debug(character.name .. " 的AI开始决策")
    
    -- 记录决策开始时间
    local start_time = os.clock()
    
    -- 分析战斗状态
    local analysis = self:analyze_battle_state(character, battle_state)
    
    -- 生成决策选项
    local options = self:generate_options(character, battle_state, analysis)
    
    -- 评估决策选项
    local evaluated_options = self:evaluate_options(character, battle_state, analysis, options)
    
    -- 选择最佳决策
    local best_decision = self:select_best_decision(evaluated_options)
    
    -- 记录决策
    self:record_decision(character, best_decision)
    
    -- 记录决策时间
    local end_time = os.clock()
    Logger.debug(character.name .. " 的AI决策完成，耗时: " .. (end_time - start_time) .. " 秒")
    
    return best_decision
end

-- 分析战斗状态
function AI:analyze_battle_state(character, battle_state)
    local analysis = {
        allies = {},
        enemies = {},
        low_health_allies = {},
        low_health_enemies = {},
        strongest_enemy = nil,
        weakest_enemy = nil,
        strongest_ally = nil,
        weakest_ally = nil,
        character_health_percentage = character.hp / character.max_hp,
        team_health_percentage = 0
    }
    
    -- 分离队友和敌人
    for _, char in ipairs(battle_state.characters) do
        if char.team_id == character.team_id then
            table.insert(analysis.allies, char)
        else
            table.insert(analysis.enemies, char)
        end
    end
    
    -- 找出低生命值的队友和敌人
    for _, ally in ipairs(analysis.allies) do
        local health_percentage = ally.hp / ally.max_hp
        if health_percentage < 0.3 then
            table.insert(analysis.low_health_allies, ally)
        end
    end
    
    for _, enemy in ipairs(analysis.enemies) do
        local health_percentage = enemy.hp / enemy.max_hp
        if health_percentage < 0.3 then
            table.insert(analysis.low_health_enemies, enemy)
        end
    end
    
    -- 找出最强和最弱的队友和敌人
    for _, ally in ipairs(analysis.allies) do
        if not analysis.strongest_ally or ally.attack > analysis.strongest_ally.attack then
            analysis.strongest_ally = ally
        end
        if not analysis.weakest_ally or ally.hp < analysis.weakest_ally.hp then
            analysis.weakest_ally = ally
        end
    end
    
    for _, enemy in ipairs(analysis.enemies) do
        if not analysis.strongest_enemy or enemy.attack > analysis.strongest_enemy.attack then
            analysis.strongest_enemy = enemy
        end
        if not analysis.weakest_enemy or enemy.hp < analysis.weakest_enemy.hp then
            analysis.weakest_enemy = enemy
        end
    end
    
    -- 计算队伍平均生命值百分比
    local total_health = 0
    local total_max_health = 0
    for _, ally in ipairs(analysis.allies) do
        total_health = total_health + ally.hp
        total_max_health = total_max_health + ally.max_hp
    end
    analysis.team_health_percentage = total_health / total_max_health
    
    return analysis
end

-- 生成决策选项
function AI:generate_options(character, battle_state, analysis)
    local options = {}
    
    -- 生成技能使用选项
    for _, skill in ipairs(character.skills) do
        if skill:is_usable(character) then
            -- 为每个可用技能生成目标选项
            for _, target in ipairs(battle_state.characters) do
                -- 检查目标是否有效
                if self:is_valid_target(skill, character, target) then
                    table.insert(options, {
                        type = "skill",
                        skill = skill,
                        target = target,
                        priority = 0
                    })
                end
            end
        end
    end
    
    -- 生成物品使用选项
    -- TODO: 实现物品使用选项生成
    
    -- 生成防御选项
    table.insert(options, {
        type = "defend",
        target = character,
        priority = 0
    })
    
    return options
end

-- 评估决策选项
function AI:evaluate_options(character, battle_state, analysis, options)
    local evaluated_options = {}
    
    for _, option in ipairs(options) do
        local score = self:evaluate_option(character, battle_state, analysis, option)
        option.score = score
        table.insert(evaluated_options, option)
    end
    
    -- 按分数排序
    table.sort(evaluated_options, function(a, b) return a.score > b.score end)
    
    return evaluated_options
end

-- 评估单个决策选项
function AI:evaluate_option(character, battle_state, analysis, option)
    local score = 0
    
    -- 根据AI性格调整评分
    if self.personality == "aggressive" then
        score = self:evaluate_aggressive(character, battle_state, analysis, option)
    elseif self.personality == "defensive" then
        score = self:evaluate_defensive(character, battle_state, analysis, option)
    elseif self.personality == "balanced" then
        score = self:evaluate_balanced(character, battle_state, analysis, option)
    elseif self.personality == "tricky" then
        score = self:evaluate_tricky(character, battle_state, analysis, option)
    end
    
    -- 根据AI难度调整评分
    score = score * self:get_difficulty_multiplier()
    
    return score
end

-- 评估攻击型决策
function AI:evaluate_aggressive(character, battle_state, analysis, option)
    local score = 0
    
    if option.type == "skill" then
        -- 优先攻击低生命值的敌人
        if option.target.team_id ~= character.team_id then
            local health_percentage = option.target.hp / option.target.max_hp
            score = score + (1 - health_percentage) * 100
            
            -- 优先使用高伤害技能
            score = score + option.skill.damage.base * 0.5
            
            -- 优先攻击最强的敌人
            if option.target == analysis.strongest_enemy then
                score = score + 50
            end
        end
    end
    
    return score
end

-- 评估防御型决策
function AI:evaluate_defensive(character, battle_state, analysis, option)
    local score = 0
    
    if option.type == "skill" then
        -- 优先治疗低生命值的队友
        if option.target.team_id == character.team_id then
            local health_percentage = option.target.hp / option.target.max_hp
            score = score + (1 - health_percentage) * 150
        end
        
        -- 优先使用防御技能
        if option.skill.type == "support" then
            score = score + 50
        end
    elseif option.type == "defend" then
        -- 自身生命值低时优先防御
        local health_percentage = character.hp / character.max_hp
        score = score + (1 - health_percentage) * 100
    end
    
    return score
end

-- 评估平衡型决策
function AI:evaluate_balanced(character, battle_state, analysis, option)
    local score = 0
    
    if option.type == "skill" then
        -- 平衡考虑攻击和防御
        if option.target.team_id ~= character.team_id then
            -- 攻击敌人
            local health_percentage = option.target.hp / option.target.max_hp
            score = score + (1 - health_percentage) * 75
        else
            -- 治疗队友
            local health_percentage = option.target.hp / option.target.max_hp
            score = score + (1 - health_percentage) * 75
        end
    end
    
    return score
end

-- 评估狡诈型决策
function AI:evaluate_tricky(character, battle_state, analysis, option)
    local score = 0
    
    if option.type == "skill" then
        -- 优先使用带有状态效果的技能
        if #option.skill.status_effects.target > 0 then
            score = score + 100
        end
        
        -- 避免重复使用相同技能
        local skill_usage_count = self:get_skill_usage_count(character, option.skill.id)
        score = score - skill_usage_count * 10
    end
    
    return score
end

-- 选择最佳决策
function AI:select_best_decision(evaluated_options)
    if #evaluated_options == 0 then
        Logger.warn("没有可用的决策选项")
        return nil
    end
    
    -- 返回评分最高的决策
    return evaluated_options[1]
end

-- 检查目标是否有效
function AI:is_valid_target(skill, character, target)
    -- 检查目标是否存活
    if not target.is_alive then
        return false
    end
    
    -- 检查目标类型
    if skill.target_type == "enemy" and target.team_id == character.team_id then
        return false
    end
    
    if skill.target_type == "ally" and target.team_id ~= character.team_id then
        return false
    end
    
    if skill.target_type == "self" and target.id ~= character.id then
        return false
    end
    
    return true
end

-- 获取技能使用次数
function AI:get_skill_usage_count(character, skill_id)
    local count = 0
    for _, usage in ipairs(self.memory.skill_usage_history) do
        if usage.character_id == character.id and usage.skill_id == skill_id then
            count = count + 1
        end
    end
    return count
end

-- 记录决策
function AI:record_decision(character, decision)
    if not decision then
        return
    end
    
    -- 记录决策
    table.insert(self.memory.previous_decisions, {
        character_id = character.id,
        decision = decision,
        timestamp = os.time()
    })
    
    -- 记录目标
    if decision.target then
        table.insert(self.memory.target_history, {
            character_id = character.id,
            target_id = decision.target.id,
            timestamp = os.time()
        })
    end
    
    -- 记录技能使用
    if decision.skill then
        table.insert(self.memory.skill_usage_history, {
            character_id = character.id,
            skill_id = decision.skill.id,
            timestamp = os.time()
        })
    end
end

-- 获取难度系数
function AI:get_difficulty_multiplier()
    local difficulty_map = {
        easy = BattleConfig.ai.difficulty_levels.easy,
        normal = BattleConfig.ai.difficulty_levels.normal,
        hard = BattleConfig.ai.difficulty_levels.hard,
        expert = BattleConfig.ai.difficulty_levels.expert
    }
    
    return difficulty_map[self.difficulty] or 1.0
end

-- 激活AI
function AI:activate()
    self.is_active = true
    Logger.debug("AI已激活: " .. self.name)
end

-- 停用AI
function AI:deactivate()
    self.is_active = false
    Logger.debug("AI已停用: " .. self.name)
end

-- 重置AI
function AI:reset()
    self:init()
    Logger.debug("AI已重置: " .. self.name)
end

-- 导出模块
return AI